<template>
  <section class="coin-manage">
    <div class="manage-title">新建/编辑积分兑换</div>

    <section class="manage-main">
      <el-form ref="form" v-loading="formloading" :model="form" :rules="rules" label-width="150px" class="main-form">
        <el-form-item label="发放名称" prop="goldGiveName">
          <el-input v-model="form.goldGiveName" placeholder="请输入发放名称" />
        </el-form-item>
        <!-- <el-form-item label="福币分类" prop="goldTypes">
          <el-cascader v-if="showtype" ref="type" v-model="form.goldTypes" :options="classifyOptions" style="width:100%" clearable :props="typeProps" />
        </el-form-item>-->
        <el-form-item label="出金账户" prop="accountId">
              <el-select :disabled="state!='create'" v-model="form.accountId" placeholder="请选择" style="width: 100%" @change="handleAccChange">
                <el-option v-for="(item, index) in accList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
        </el-form-item>
        <el-form-item label="发放起止时间" required>
          <el-col :span="8">
            <el-form-item label prop="giveSrartTime">
              <el-date-picker v-model="form.giveSrartTime" type="datetime" placeholder="选择发放开始日期" style="width: 100%;" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="8">
            <el-form-item label prop="giveEndTime">
              <el-date-picker
                v-model="form.giveEndTime"
                :disabled="notimelimit"
                type="datetime"
                placeholder="选择发放结束日期"
                style="width: 100%;"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="6">
            <el-checkbox v-model="notimelimit">长期有效</el-checkbox>
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="是否定向" prop="isDirectional">
          <el-radio-group v-model="form.isDirectional">
            <el-radio v-for="v in dict.ZPID" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="发放说明" prop="giveExplain">
          <el-input v-model="form.giveExplain" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" placeholder="请输入发放说明" />
        </el-form-item>
        <el-form-item label="兑换比例" prop="exchangeRatio">
          <el-input v-model.number="form.exchangeRatio" placeholder="请输入兑换比例">
            <template slot="append">多少积分兑换一元钱</template>
          </el-input>
        </el-form-item>
        <el-form-item label="个人兑换上限" prop="exchangeSelfToplimit">
          <el-row>
            <el-col :span="12">
              <el-input v-model.number="form.exchangeSelfToplimit" :disabled="toplimit" placeholder="请输入个人兑换上限" />
            </el-col>
            <el-col :span="3">&nbsp;单位（元）</el-col>
            <el-col :span="8">
              <el-checkbox v-model="toplimit">无上限</el-checkbox>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- <el-form-item label="福币失效时间" prop="goldInvalidTime">
          <el-row>
            <el-col :span="12">
              <el-date-picker
                v-model="form.goldInvalidTime"
                :disabled="notimelimit4glod"
                type="datetime"
                placeholder="选择日期"
                style="width: 100%;"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-col>
            <el-col :span="2">&nbsp;</el-col>
            <el-col :span="8">
              <el-checkbox v-model="notimelimit4glod">长期有效</el-checkbox>
            </el-col>
          </el-row>
        </el-form-item>-->
      </el-form>
    </section>

    <div class="manage-footer">
      <el-button style="padding: 8px 30px;" @click="handleCancel">取消</el-button>
      <el-button style="padding: 8px 30px;" type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </section>
</template>
<script>
import { specialText, int, doublescore, intwith } from '@/utils/validate'
import { getDictByCode, getClassifyTree, insert, update, get,getAcc } from './../api/coin'
import CryptoJS from '@/utils/aesJiaJM'
export default {
  name: 'SpecialManage',
  data() {
    return {
      state: 'create',
      formloading: false,
      accList:[],
      form: {
        id: '',
        goldGiveName: '',
        accountId:'',
        goldType: 'type',
        goldTypes: [],
        giveExplain: '',
        giveSrartTime: '',
        giveEndTime: '',
        goldCount: 0,
        gaveGold: 0,
        isDirectional: 'ZPID02',
        exchangeRatio: '',
        exchangeSelfToplimit: '',
        goldInvalidTime: '',
        giveParams: '',
        status: 'GOLDPOOLSTATUS02'
      },
      rules: {
        goldGiveName: [
          { required: true, message: '请输入发放名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        accountId: [{ required: true, message: '请选择出金账户', trigger: 'change' }],
        giveExplain: [{ required: true, message: '请输入发放说明', trigger: 'blur' }],
        isDirectional: [{ required: true, message: '请选择是否定向', trigger: 'blur' }],
        goldTypes: [{ required: true, message: '请选择福币分类', trigger: 'blur' }],
        giveSrartTime: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        giveEndTime: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        goldCount: [
          { required: true, message: '请输入总量', trigger: 'blur' },
          { trigger: 'blur', validator: intwith }
        ],
        exchangeRatio: [
          { required: true, message: '请输入兑换比例', trigger: 'blur' },
          { trigger: 'blur', validator: int }
        ],
        exchangeSelfToplimit: [
          { required: true, message: '请输入个人兑换上限', trigger: 'blur' },
          { trigger: 'blur', validator: doublescore }
        ],
        goldInvalidTime: [
          { required: true, message: '请选择失效时间', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      },
      typeProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      classifyOptions: [],
      toplimit: false,
      notimelimit: false,
      notimelimit4glod: false,
      showtype: false,
      dict: {
        GOLDPOOLSTATUS: []
      }
    }
  },
  watch: {
    'form.goldTypes': {
      handler(newName, oldName) {
        if (this.$refs.type) {
          this.$refs.type.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    },
    toplimit(val) {
      if (val) {
        this.form.exchangeSelfToplimit = 0
      } else {
        this.form.exchangeSelfToplimit = ''
      }
    },
    notimelimit(val) {
      if (val) {
        this.form.giveEndTime = '2099-12-31 23:59:59'
      } else {
        this.form.giveEndTime = ''
      }
    },
    notimelimit4glod(val) {
      if (val) {
        this.form.goldInvalidTime = '2099-12-31 23:59:59'
      } else {
        this.form.goldInvalidTime = ''
      }
    }
  },
 async  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    // for (const key in this.dict) {
    //   this.getDict(key)
    // }
    // this.getClassify()
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showtype = true
    }
      this.accList= await this.getAccFun()
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 获取分类
     */
    getClassify() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'FLZXFL01' }).then(({ data }) => {
          this.classifyOptions = data.data || []
        }).catch(error => {
          reject(error)
        })
      })
    },

    handleSubmit() {
      this.state === 'create' ? this.createData() : this.updateData()
    },

    handleCancel() {
      this.$router.push({ path:this.$filterPath("index")})
    },

    /*
    * 新增
    * */
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const {
            id,
            accountId,
            goldGiveName,
            giveExplain,
            giveSrartTime,
            giveEndTime,
            isDirectional,
            exchangeRatio,
            goldInvalidTime,
            giveParams,
            status
          } = this.form
          return new Promise((resolve, reject) => {
            insert({
              id,
              accountId,
              goldGiveName,
              giveExplain,
              giveSrartTime,
              giveEndTime,
              isDirectional,
              exchangeRatio,
              goldInvalidTime,
              giveParams,
              status,
              exchangeSelfToplimit: this.toplimit ? '0' : this.form.exchangeSelfToplimit,
              goldType: this.form.goldTypes.length > 0 ? this.form.goldTypes[this.form.goldTypes.length - 1] : 'type'
            }).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1500
              })
							this.$router.push({ path:this.$filterPath("index")})
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    /**
     * 编辑提交
     */
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const {
            id,
            goldGiveName,
            giveExplain,
            giveSrartTime,
            giveEndTime,
            isDirectional,
            exchangeRatio,
            goldInvalidTime,
            giveParams,
            status
          } = this.form
          return new Promise((resolve, reject) => {
            update({
              id,
              goldGiveName,
              giveExplain,
              giveSrartTime,
              giveEndTime,
              isDirectional,
              exchangeRatio,
              goldInvalidTime,
              giveParams,
              status,
              exchangeSelfToplimit: this.toplimit ? '0' : this.form.exchangeSelfToplimit,
              goldType: this.form.goldTypes.length > 0 ? this.form.goldTypes[this.form.goldTypes.length - 1] : 'type'
            }).then(() => {
              loading.close()
              this.dialogFormVisible = false
              this.$message({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
							this.$router.push({ path:this.$filterPath("index")})
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    cancel() {
			this.$router.push({ path:this.$filterPath("index")})
    },

    /**
     * 获取详情
     */
   getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(id).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'goldTypes') {
              this.form[key] = (data.goldTypeIds && data.goldTypeIds.split(',')) || []
            } else if (key === 'exchangeSelfToplimit') {
              this.form[key] = data[key]
              if (this.form[key] === 0 || this.form[key] === '0') {
                this.toplimit = true
              }
            } else if (key === 'goldInvalidTime') {
              this.form[key] = data[key]
              if (this.form[key] === '2099-12-31 23:59:59') {
                this.notimelimit4glod = true
              }
            } else if (key === 'giveEndTime') {
              this.form[key] = data[key]
              if (this.form[key] === '2099-12-31 23:59:59') {
                this.notimelimit = true
              }
            } else {
              this.form[key] = data[key]
            }
          }
          // this.accList= await this.getAccFun()
      
          console.log(this.form)
          this.showtype = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleAccChange(val){},
    getAccFun() {

      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getAcc().then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}(${CryptoJS.$aesJieM(a.accountNumber)})`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
  }
}
</script>
<style lang="scss">
@import '@/styles/mixin.scss';
.coin-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
  }

  .main-form {
    width: 1000px !important;
    margin: 0 auto;
    .line {
      text-align: center;
    }
    .form-card {
      margin-top: 20px;
      .el-card__body {
        max-width: 90%;
        margin: 0 auto;
      }
    }
  }

  .manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
